package com.youlu.campus.service.english;

import com.google.common.collect.Lists;
import com.youlu.campus.entity.ActivityQaInfo;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.english.ActivityGroup;
import com.youlu.campus.entity.english.ActivityGroupQaType;
import com.youlu.campus.entity.english.ActivityQaFeeDetail;
import com.youlu.campus.entity.english.UserCompetitionFee;
import com.youlu.campus.entity.english.vo.request.ActivityGroupCreatedCommand;
import com.youlu.campus.entity.english.vo.request.ActivityGroupQuery;
import com.youlu.campus.entity.english.vo.response.ActivityGroupPageResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ActivityGroupService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserCompetitionService userCompetitionService;

    @Autowired
    private UserCompetitionFeeService userCompetitionFeeService;


    public ActivityGroup findById(String activityGroupId){
       return this.mongoTemplate.findById(activityGroupId,ActivityGroup.class);
    }

    public Boolean findByActivityId(String activityId){
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId));
        return this.mongoTemplate.exists(query,ActivityGroup.class);
    }


    public Map<String,Object> home(UserPO currentUser){
        Boolean exist = userCompetitionService.exist(currentUser.getId());
        Map<String,Object> map = new HashMap<>(2);
        map.put("register",exist);
        map.put("list",groupList(currentUser));
        return map;
    }

    public List<ActivityGroupPageResponse> groupList(UserPO currentUser){
        List<ActivityGroup> list = this.mongoTemplate.findAll(ActivityGroup.class);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
      return list.stream().map(activityGroup -> {
            ActivityGroupPageResponse activityGroupPage = new ActivityGroupPageResponse();
            activityGroupPage.setActivityGroupId(activityGroup.getId());
            activityGroupPage.setGroupName(activityGroup.getGroupName());
          activityGroupPage.setActivityId(activityGroup.getActivityId());
          activityGroupPage.setDescription(activityGroup.getDescription());
          activityGroupPage.setOrder(activityGroup.getOrder());
          activityGroupPage.setStatus(activityGroup.getStatus());
          if(Objects.nonNull(currentUser)){
              UserCompetitionFee userCompetitionFee = userCompetitionFeeService.findActivityGroupId(currentUser.getId(),
                      activityGroup.getId());
              if(Objects.nonNull(userCompetitionFee)){
                  activityGroupPage.setQaTypeList(userCompetitionFee.getBuyQaTypeList().stream().map(qaType->{
                      if(ActivityGroupQaType.QA_FU_SAI.equals(qaType.getCode())){
                          qaType.setName("省赛");
                      }
                      if(ActivityGroupQaType.QA_JUE_SAI.equals(qaType.getCode())){
                          qaType.setName("全国决赛");
                      }
                      return qaType;
                  }).collect(Collectors.toList()));
                  activityGroupPage.setFeeTypeCode(userCompetitionFee.getFeeTypeCode());
              }
              Optional<ActivityGroupQaType> qaTypeOptional = activityGroup.getQaTypeList().stream().filter(qaType -> ActivityGroupQaType.QA_CHU_SAI.equals(qaType.getCode())).findAny();
              if(qaTypeOptional.isPresent()){
                  activityGroupPage.setChuSaiQaCode(qaTypeOptional.get().getCode());
                  activityGroupPage.setChuSaiQaName(qaTypeOptional.get().getName());
                  activityGroupPage.setChuSaiQaId(qaTypeOptional.get().getQaInfoId());
              }
          }
            return activityGroupPage;
        }).collect(Collectors.toList()).stream().sorted(Comparator.comparing(ActivityGroupPageResponse::getOrder)).collect(Collectors.toList());
    }

    public ActivityGroupPageResponse detail(String activityGroupId){
        ActivityGroup activityGroup = this.mongoTemplate.findById(activityGroupId, ActivityGroup.class);
        if(Objects.isNull(activityGroup)){
            return null;
        }
        ActivityGroupPageResponse activityGroupPageResponse = buildDetail(activityGroup);
        return activityGroupPageResponse;
    }

    public Page<ActivityGroupPageResponse> list(){
        Query query = new Query();
        List<ActivityGroup> list = this.mongoTemplate.find(query, ActivityGroup.class);
        List<ActivityGroupPageResponse> result = list.stream().map(activityGroup -> {
           return buildDetail(activityGroup);
        }).collect(Collectors.toList());
        return new PageImpl<>(result);
    }

    private ActivityGroupPageResponse buildDetail(ActivityGroup activityGroup){
        ActivityGroupPageResponse groupPageResponse = new ActivityGroupPageResponse();
        groupPageResponse.setActivityGroupId(activityGroup.getId());
        groupPageResponse.setDescription(activityGroup.getDescription());
        if(CollectionUtils.isNotEmpty(activityGroup.getQaTypeList())){
            Optional<ActivityGroupQaType> chuSaiOptional =
                    activityGroup.getQaTypeList().stream().filter(qaType -> ActivityGroupQaType.QA_CHU_SAI.equals(qaType.getCode())).findFirst();
            if (chuSaiOptional.isPresent()) {
                String qaInfoId = chuSaiOptional.get().getQaInfoId();
                ActivityQaInfo activityQaInfo = this.mongoTemplate.findById(qaInfoId, ActivityQaInfo.class);
                if(Objects.nonNull(activityQaInfo)){
                    groupPageResponse.setChuSaiQaId(qaInfoId);
                    groupPageResponse.setChuSaiQaName(activityQaInfo.getName());
                }
            }
            Optional<ActivityGroupQaType> fuSaiOptional =
                    activityGroup.getQaTypeList().stream().filter(qaType -> ActivityGroupQaType.QA_FU_SAI.equals(qaType.getCode())).findFirst();
            if (fuSaiOptional.isPresent()) {
                String qaInfoId = fuSaiOptional.get().getQaInfoId();
                ActivityQaInfo activityQaInfo = this.mongoTemplate.findById(qaInfoId, ActivityQaInfo.class);
                if(Objects.nonNull(activityQaInfo)){
                    groupPageResponse.setFuSaiQaId(qaInfoId);
                    groupPageResponse.setFuSaiQaName(activityQaInfo.getName());
                }
            }
            Optional<ActivityGroupQaType> jueSaiOptional =
                    activityGroup.getQaTypeList().stream().filter(qaType -> ActivityGroupQaType.QA_JUE_SAI.equals(qaType.getCode())).findFirst();
            if (jueSaiOptional.isPresent()) {
                String qaInfoId = jueSaiOptional.get().getQaInfoId();
                ActivityQaInfo activityQaInfo = this.mongoTemplate.findById(qaInfoId, ActivityQaInfo.class);
                if(Objects.nonNull(activityQaInfo)){
                    groupPageResponse.setJueSaiQaId(qaInfoId);
                    groupPageResponse.setJueSaiQaName(activityQaInfo.getName());
                }
            }
        }
        groupPageResponse.setActivityName(activityGroup.getActivityName());
        groupPageResponse.setGroupName(activityGroup.getGroupName());
        return groupPageResponse;
    }


   public void save(ActivityGroupCreatedCommand createdCommand){
       String activityGroupId = createdCommand.getActivityGroupId();
       ActivityGroup activityGroup = this.mongoTemplate.findById(activityGroupId, ActivityGroup.class);
       if(Objects.isNull(activityGroup)){
           return;
       }
       activityGroup.setDescription(createdCommand.getDescription());
       List<ActivityGroupQaType> qaTypeList = Lists.newArrayListWithCapacity(3);
       ActivityGroupQaType groupQaType = null;
       //初赛题库Id
       if(StringUtils.isNotBlank(createdCommand.getChuSaiQaId())){
           groupQaType = new ActivityGroupQaType();
           groupQaType.setQaInfoId(createdCommand.getChuSaiQaId());
           groupQaType.setName("初赛");
           groupQaType.setAliasName(activityGroup.getGroupName()+groupQaType.getName());
           groupQaType.setCode(ActivityGroupQaType.QA_CHU_SAI);
           qaTypeList.add(groupQaType);
       }
        String fuSaiQaId = createdCommand.getFuSaiQaId();
       if(StringUtils.isNotBlank(fuSaiQaId)){
           groupQaType = new ActivityGroupQaType();
           groupQaType.setQaInfoId(fuSaiQaId);
           groupQaType.setName("复赛");
           groupQaType.setAliasName(activityGroup.getGroupName()+groupQaType.getName());
           groupQaType.setCode(ActivityGroupQaType.QA_FU_SAI);
           qaTypeList.add(groupQaType);
       }
       String jueSaiQaId = createdCommand.getJueSaiQaId();
       if(StringUtils.isNotBlank(jueSaiQaId)){
           groupQaType = new ActivityGroupQaType();
           groupQaType.setQaInfoId(jueSaiQaId);
           groupQaType.setName("决赛");
           groupQaType.setAliasName(activityGroup.getGroupName()+groupQaType.getName());
           groupQaType.setCode(ActivityGroupQaType.QA_JUE_SAI);
           qaTypeList.add(groupQaType);
       }
       activityGroup.setQaTypeList(qaTypeList);
       this.mongoTemplate.save(activityGroup);
   }



}
